package service

import (
	"errors"
	"time"
	"vrcm/src/vrcm/app/admin/models/live_schedule"
	"vrcm/src/vrcm/app/admin/service/dto/live_schedule"
	"vrcm/src/vrcm/common/service"

	"gorm.io/gorm"

	"vrcm/src/vrcm/common/actions"
	cDto "vrcm/src/vrcm/common/dto"
)

type SourceGroupService struct {
	service.Service
}

// GetPage 获取SourceGroup列表
func (e *SourceGroupService) GetPage(c *dto.SourceGroupGetPageReq, p *actions.DataPermission, list *[]live_schedule.SourceGroup, count *int64) error {
	var err error
	var data live_schedule.SourceGroup

	if len(c.GroupName) > 0 {

	}
	err = e.Orm.Model(&data).
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
			actions.Permission(data.TableName(), p),
		).
		Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("SourceGroupService GetPage error:%s \r\n", err)
		return err
	}
	return nil
}

// Get 获取SourceGroup对象
func (e *SourceGroupService) Get(d *dto.SourceGroupGetReq, p *actions.DataPermission, model *live_schedule.SourceGroup) error {
	var data live_schedule.SourceGroup

	err := e.Orm.Model(&data).
		Scopes(
			actions.Permission(data.TableName(), p),
		).
		First(model, d.GetId()).Error
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		err = errors.New("查看对象不存在或无权查看")
		e.Log.Errorf("Service GetSourceGroup error:%s \r\n", err)
		return err
	}
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return err
	}
	return nil
}

// Insert 创建SourceGroup对象
func (e *SourceGroupService) Insert(c *dto.SourceGroupInsertReq) error {
	var err error
	var data live_schedule.SourceGroup
	c.Generate(&data)
	err = e.Orm.Create(&data).Error
	if err != nil {
		e.Log.Errorf("SourceGroupService Insert error:%s \r\n", err)
		return err
	}
	return nil
}

// Update 修改SourceGroup对象
func (e *SourceGroupService) Update(c *dto.SourceGroupUpdateReq) error {
	var err error
	var data = live_schedule.SourceGroup{}
	e.Orm.First(&data, c.GetId())
	if data.Id <= 0 {
		return errors.New("分组不存在")
	}
	c.Generate(&data)

	db := e.Orm.Save(&data)
	if err = db.Error; err != nil {
		e.Log.Errorf("SourceGroupService Save error:%s \r\n", err)
		return err
	}
	return nil
}

// Remove 删除SourceGroup
func (e *SourceGroupService) Remove(d *dto.SourceGroupDeleteReq) error {

	tx := e.Orm.Begin()
	defer func() {
		if r := recover(); r != nil {
			e.Log.Errorf("SourceGroupService Remove error:%s \r\n", r)
			tx.Rollback()
			//return
		}
	}()
	if err := tx.Error; err != nil {
		return err
	}

	var data live_schedule.SourceGroup

	db := tx.Model(&data).Delete(&data, d.GetId())
	if err := db.Error; err != nil {
		e.Log.Errorf("Service RemoveSourceGroup error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	err := tx.Model(live_schedule.SourceGroupRelation{}).Where("group_id in ?", d.GetId()).Delete(&live_schedule.SourceGroupRelation{}).Error
	if err != nil {
		e.Log.Errorf("Service RemoveSourceGroup error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	tx.Commit()
	return nil
}

func (e *SourceGroupService) SourceGroupRelation(d *dto.SourceGroupRelationReq) error {

	tx := e.Orm.Begin()
	defer func() {
		if r := recover(); r != nil {
			e.Log.Errorf("Service SourceGroupRelation error:%s \r\n", r)
			tx.Rollback()
			//return
		}
	}()
	if err := tx.Error; err != nil {
		return err
	}

	//删除信源和组关系
	var s live_schedule.SourceGroupRelation
	err := tx.Model(&live_schedule.SourceGroupRelation{}).Where("tenant_id=? and group_id = ?", d.TenantId, d.GroupId).Delete(&s).Error
	if err != nil {
		e.Log.Errorf("delete SourceGroupRelation error:%s \r\n", err)
		tx.Rollback()
		return err
	}

	//插入新信源和组关系
	now := time.Now().Unix()
	relations := make([]live_schedule.SourceGroupRelation, 0, 5)
	sourceIdMap := make(map[int]struct{})
	for _, v := range d.SourceIds {
		r := live_schedule.SourceGroupRelation{}
		r.TenantId = d.TenantId
		r.GroupId = d.GroupId
		r.SourceId = v
		r.CreateTime = now
		r.UpdateTime = now
		sourceIdMap[v] = struct{}{}
		relations = append(relations, r)
	}

	//取消所有信源绑定的时候 需要删除调度上车点对应的组新信源
	if len(relations) > 0 {
		err = tx.Create(relations).Error
		if err != nil {
			e.Log.Errorf("insert SourceGroupRelation error:%s \r\n", err)
			tx.Rollback()
			return err
		}
	}

	tx.Commit()

	return nil
}

// GetDetail 获取信源组下面的信源
func (e *SourceGroupService) GetDetail(d *dto.SourceGetDetailReq, count *int64) (*[]dto.SourceModelRes, error) {

	s := SourceBasicService{}
	s.Orm = e.Orm
	s.Log = e.Log

	ids := make([]int, 0, 5)
	e.Orm.Model(&live_schedule.SourceGroupRelation{}).Select("source_id").Where("group_id=?", d.Id).Find(&ids)

	res := make([]dto.SourceModelRes, 0, 5)
	if len(ids) > 0 {
		data, err := s.GetPage(&dto.SourceBasicGetPageReq{Pagination: d.Pagination, SourceIds: ids, IsDelete: 2}, count)
		if err != nil {
			e.Log.Errorf("GetDetail  error:%s \r\n", err)
			return nil, err
		}
		res = *data
	}

	return &res, nil
}
